package cn.edu.nju.freshdelivery.util;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

/**
 * 
 * @author ZhangZu 用来获取用户的当前位置
 */
public class LocationGetter {
	private static LocationGetter locationGetter = new LocationGetter();
	private Context context = null;
	/** manage the location */
	private LocationManager locMgr = null;

	/** listen to location events such as location change */
	private LocationListener locListener = null;

	private Location location;

	private String address;

	private LocationGetter() {
	}

	public static LocationGetter getInstance() {
		return locationGetter;
	}

	public void init(Context context) {
		this.context = context;
		locMgr = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		generateCityName();
		
		locListener = new LocationListener() {
			public void onLocationChanged(Location location) {
				LocationGetter.this.location = location;
				generateCityName();
			}

			public void onProviderDisabled(String provider) {
			}

			public void onProviderEnabled(String provider) {
			}

			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}
		};
		locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, // 1min
				100, // minDistance in meters
				locListener);

	}

	public Location getLocation() {
		return location;
	}

	public String getAddress() {
		return address;
	}

	private void generateCityName() {
		if (address != null || location == null)
			return;
		List<Address> addList = null;
		Geocoder ge = new Geocoder(context, Locale.CHINA);
		try {
			addList = ge.getFromLocation(location.getLatitude(),
					location.getLongitude(), 1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("getlist");
		if (addList != null && addList.size() > 0) {
			System.out.println("not null");
			Address ad = addList.get(0);
			address = ad.getCountryName() + "-" + ad.getAdminArea() + "-"
					+ ad.getLocality();
		}
		Toast.makeText(context, address, Toast.LENGTH_SHORT).show();
	}
}
